<?php

namespace app\common\model;

use think\Exception;
use think\Log;
use think\Model;

class BaseModel extends Model
{
    //过滤数据，在传入的大量数据中找到本模型所对应的数据，并返回出来
    public function dataFilter($data){
        $fields=$this->getTableFields();
        $correctData=[];
        foreach($data as $key=>$value){
            if(in_array($key,$fields)){
                $correctData[$key]=$value;
            }
        }
        return $correctData;
    }

    //判断某一字段的添加重复性
    public function checkAddUnique($fieldName,$value){
        $isset=$this->where($fieldName,"=",$value)->find();
        return $isset;
    }

    //判断某一字段的编辑重复性
    public function checkEditUnique($fieldName,$value,$primary_id_name,$primary_id_value){
        $condition=[];
        $condition[$primary_id_name]=['<>',$primary_id_value];
        $condition[$fieldName]=['=',$value];
        return $this->where($condition)->find();
    }



    //信息添加
    public function dataAdd($data){
        $returnData=[];
        try{
            $result=$this->insert($data);
        }catch (Exception $exception){
            $this->assembleData($returnData,"数据插入异常",$exception->getMessage());
            return $returnData;
        }
        if(!$result){
            $this->assembleData($returnData,"数据插入失败");
        }else{
            $this->assembleData($returnData,"1");
        }
        return $returnData;
    }


    //信息编辑
    //按照指定的字段进行条件更新
    public function dataEdit($data,$primary_key_name,$primary_key_value){
        $returnData=[];
        try{
            //更新条件
            //注意condition条件的写法  ["attr_id"=>['eq',$attr_id]]; 后面的value是一个两个长度为二的索引数组，不是关联数组
            $condition[$primary_key_name]=['eq',$primary_key_value];
            $result=$this->where($condition)->update($data);
        }catch (Exception $exception){
            $this->assembleData($returnData,"数据编辑异常",$exception->getMessage()."|".$this->getLastSql());
            return $returnData;
        }
        if(!$result){
            $this->assembleData($returnData,"数据未发生变化");
        }else{
            $this->assembleData($returnData,"1");
        }
        return $returnData;
    }




    //组装返回数据
    public function assembleData(&$data,$msg=null,$errMsg=null){
        if($msg!=null){
            $data['msg']=$msg;
        }
        if($errMsg!=null){
            $data['errMsg']=$errMsg;
        }
    }

    //处理返回数据，记录日志
    //$positionStr就是用来给日志记录的时候，添加日志定位信息的
    public function handleReturnData($returnData,$positionStr){
        if($returnData['msg']!=1){

            Log::write($positionStr.(array_key_exists("errMsg",$returnData)?$returnData['errMsg']:$returnData['msg']));
        }
        return $returnData['msg'];
    }


    //获取指定条件下的记录数
    public function getCount($condition){
        $countData=$this->field("count(*)")
            ->where($condition)
            ->select();
        return $countData[0]['count(*)'];
    }

}
